package com.hhd.flow.controller;

import com.hhd.flow.vo.Result;
import com.hhd.flow.vo.VariableVoGroup;
import com.hhd.flow.vo.VariableVoGroups;
import com.hhd.flow.engine.FlowEngine;
import com.hhd.flow.engine.variable.FlowVariableDefinition;
import com.hhd.flow.engine.variable.FlowVariablesContainer;
import com.hhd.flow.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/flow/variables")
public class VariableController {

    @Autowired
    FlowEngine flowEngine;

    @GetMapping("/loadVariablesByFormType")
    public Result loadVariablesByFormType(String formType) {
        FlowVariablesContainer flowVariablesContainer = flowEngine.loadVariableContainerForDefinition(formType, null, null);

        List<FlowVariableDefinition> flowVariableDefinitions = flowVariablesContainer.getFlowVariableDefinitions();

        if (CommonUtils.isEmpty(flowVariableDefinitions)) return Result.ok();

        return Result.ok(createGroup(flowVariableDefinitions));
    }

    private VariableVoGroups createGroup(List<FlowVariableDefinition> flowVariableDefinitions) {
        VariableVoGroups res = new VariableVoGroups();
        Map<String, VariableVoGroup> groupMap = new HashMap<>();
        for (FlowVariableDefinition flowVariableDefinition : flowVariableDefinitions) {
            if (groupMap.containsKey(flowVariableDefinition.getGroupName())) {
                groupMap.get(flowVariableDefinition.getGroupName()).getVariables().add(flowVariableDefinition);
            } else {
                VariableVoGroup variableVoGroup = new VariableVoGroup();
                variableVoGroup.setGroupName(flowVariableDefinition.getGroupName());
                variableVoGroup.getVariables().add(flowVariableDefinition);

                groupMap.put(variableVoGroup.getGroupName(), variableVoGroup);
                res.add(variableVoGroup);
            }
        }
        return res;
    }
}
